package com.itmayiedu.controller;

import com.itmayiedu.base.ResponseBase;
import com.itmayiedu.constants.Constants;
import com.itmayiedu.entity.UserEntity;
import com.itmayiedu.feign.MemberServiceFeign;
import com.itmayiedu.utils.CookieUtil;
//import com.qq.connect.QQConnectException;
//import com.qq.connect.oauth.Oauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;

/**
 * @Author cht 【wonderfor@vip.qq.com】
 * @Date 2018/10/24
 */
@Controller
public class LoginController {

    @Autowired
    private MemberServiceFeign memberServiceFeign;
    private static final String LOGIN = "login";
    private static final String INDEX = "redirect:/";

    @GetMapping(value = "/login")
    public String login() {
        return LOGIN;
    }

    @PostMapping(value = "/login")
    public String login(UserEntity userEntity, HttpServletRequest request, HttpServletResponse response) {
        //1.验证参数
        //2.调用登录接口,获取token信息
        ResponseBase loginBase = memberServiceFeign.login(userEntity);
        if(!loginBase.getRtnCode().equals(Constants.HTTP_RES_CODE_200)) {
            request.setAttribute("error", "账号或密码错误!");
            return LOGIN;
        }

        LinkedHashMap loginData = (LinkedHashMap) loginBase.getData();
        String memberToken = (String) loginData.get("memberToken");
        if(StringUtils.isEmpty(memberToken)) {
            request.setAttribute("error", "会话已失效!");
            return LOGIN;
        }

        //3.将token存入cookie
        CookieUtil.addCookie(response, Constants.COOKIE_MEMBER_TOKEN, memberToken, Constants.COOKIE_TOKEN_MEMBER_TIME);
        return INDEX;
    }

//    //生成QQ授权登录链接
////    @RequestMapping("/locaQQLogin")
////    public String locaQQLogin(HttpServletRequest request) throws QQConnectException {
////        //生成授权链接
////        String authorizeURL = new Oauth().getAuthorizeURL(request);
////        return "redirect:" + authorizeURL;
////    }

    @RequestMapping("/qqLoginCallback")
    public String qqLoginCallback() {
        return "1";
    }
}
